<!-- 机构管理 -->
<template>
  <div class="jq-table h-full flex-col">
    <div class="packageCardcontainer">
      <template v-for="boxContent in contentList" :key="boxContent?.title">
        <PackageCard class="card" :boxContent="boxContent" />
      </template>
    </div>

    <SearchForm
      @handle-reset-form-datas="handleResetFormDatas"
      :searchForm="searchForm"
      @handle-search="handleSearch"
      @chanFormValue="chanFormValue"
    />
    <div class="page-card h-full" v-loading="loading">
      <JqTable
        :tableColumn="tableColumn"
        :tableButtons="tableButtons"
        :itemsButtons="itemsButtons"
        :data="tableData"
        :page="page"
        :loading="loading"
        @handle-selection-change="handleSelectionChange"
        @handle-size-change="handleSizeChange"
        @handle-current-change="handleCurrentChange"
      >
      <template #statusText>
        <el-table-column
            show-overflow-tooltip
            :min-width="100"
            prop="statusText"
            label="状态"
            fit="true"
            show-header="true"
            align="left"
          >
            <template #default="scope">
              <div style="display: flex; align-items: center">
                <span :class="scope.row.status ===  1 ? `point1` : scope.row.status ===  2 ? `point3`:  scope.row.status ===  3 ? `point4`: 'point2'"></span>
                <span>{{ scope.row['statusText'] }}</span>
              </div>
            </template>
          </el-table-column>
      </template>
      </JqTable>
      <!-- <AddOrUpdate
        ref="addOrUpdateRef"
        :visible='visible'
        @clear-form-datas="clearFormDatas"
        @onCancel="onCancel"
        @onConfirm="onConfirm"
      /> -->
      <AddOrUpdate v-if="showDialog" v-model:dialogVisible="showDialog" ref="addOrUpdateRef" :dialogDatas="dialogDatas"
        @update-list="updateList" />
      <Rechargeable ref="rechargeableRef" @update-list="updateList"/>
      <Package ref="packageRef" />
      <rechargeRecord ref="rechargeRecordRef"  @update-list="updateList"/>
    </div>
  </div>
</template>

<script lang="ts" setup>
defineOptions({ name: 'Cooperation' }); //机构管理
interface Row {
  id: number;
  status: number;
}
import { reactive, ref, onMounted, computed } from 'vue';
import { useTable } from '@/hooks/useTable';
// import { userList } from '@/api/user';
import {
  orgStatisticsRequest,
  orgGetOrgListRequest,
  rechargeCheckPointsRequest,
  pauseOrgRequest,
  exportRequest,
  editOrgRequest
} from '@/api/cooperation/index';
import { JqTable } from '@/components/Table/index';
import { AddOrUpdate, Rechargeable, Package, rechargeRecord } from './components';

import { getOrgDetailRequest, addOrgRequest } from '@/api/cooperation';
import { PackageCard } from '@/components/PackageCard/index';
import { useRoute, useRouter } from 'vue-router';
import { getEnumListRequest,salesOptionsRequest } from '@/api/common';
import { useRouteStore } from '@/store';

const router = useRouter();
const routeStore = useRouteStore();

let dialogDatas = reactive({});
let visible = ref(false);//控制弹出框关闭隐藏

const showDialog = ref(false)
/* 表单查询 */
const handleSearch =  (searchFormParamsDatats: {}) => {
  Object.assign(searchFormParams, searchFormParamsDatats);
  getList();
  // handleResetFormDatas();
};
const addOrUpdateRef = ref();
const rechargeableRef = ref();
const packageRef = ref();
const rechargeRecordRef = ref();
let currentClickRowDatas = ref(); //当前操作的表格明细

let institutionStatusEnumDatas = reactive([]); //状态下拉数据
let cutomerLevelEnumDatas = reactive([]); //客户级别下拉数据
let institutionSourceEnumDatas = reactive([]); //客户级别下拉数据
let institutionTypeEnumDatas = reactive([]); //客户类型下拉数据
let industryTyeEnumDatas = reactive([]); //行业类型下拉数据
let orgTypeEnumDatas = reactive([]); //组织类型下拉数据
let salesOptionsDatas = reactive([]); //我方销售人员下拉数据


const currentMenudatas = computed(() => routeStore.currentMenudatas);

let searchForm = reactive([
  {
    type: 'input',
    value: '',
    label: '机构名称',
    placeholder:'请输入机构名称',
    eName: 'orgName'
  },

  {
    type: 'cascader',
    value: [],
    label: '所在地区',
    eName: 'area',
    keys: ['provinceId', 'cityId', 'districtId']
  },

  {
    type: 'select',
    value: '',
    label: '机构状态',
    options: () => {
      return institutionStatusEnumDatas;
    },
    eName: 'status'
  },
  {
    type: 'select',
    value: '',
    label: '机构类型',
    options: () => {
      return institutionTypeEnumDatas;
    },
    eName: 'institutionType'
  },
  {
    type: 'select',
    value: '',
    label: '客户级别',
    options: () => {
      return cutomerLevelEnumDatas;
    },
    eName: 'customerLevel'
  },
  // {
  //   type: 'select',
  //   value: '',
  //   label: '来源',
  //   options: () => {
  //     return institutionSourceEnumDatas;
  //   },
  //   eName: 'source'
  // },
  // {
  //   type: 'input',
  //   value: '',
  //   label: '联系人姓名',
  //   eName: 'contactPerson'
  // },
  // {
  //   type: 'input',
  //   value: '',
  //   label: '联系人手机号',
  //   eName: 'phoneNumber'
  // },

  // {
  //   type: 'select',
  //   value: '',
  //   label: '我方销售人员',
  //   options: () => {
  //     return salesOptionsDatas;
  //   },
  //   eName: 'salesPersonId'
  // },

  {
    type: 'date',
    value: '',
    label: '创建时间',
    eName: 'createDate'
  }
]);

const tableColumn = reactive([
  //内置
  { label: '组织机构名称', prop: 'orgName',minWidth: '120' },
  { label: '所在地区', prop: 'area',minWidth: '80' },
  { label: '机构类型', prop: 'institutionTypeText',minWidth: '80' },
  { label: '客户级别', prop: 'customerLevelText',minWidth: '80' },
  { label: '来源', prop: 'sourceText',minWidth: '80' },
  { label: '创建时间', prop: 'createTime',minWidth: '170' },
  { label: '状态', prop: 'statusText',minWidth: '100' ,slot: true},
  { label: '账期额度点数', prop: 'creditLimitPoints',minWidth: '120' },
  { label: '累计已使用点数', prop: 'totalUsedPoints',minWidth: '140' },
  { label: '已用额度点数', prop: 'creditLimitUsedPoints',minWidth: '120' },
  { label: '现充余额点数', prop: 'rechargeBalancePoints',minWidth: '120' },
  { label: '剩余点数', prop: 'remainingPoints',minWidth: '80' },
  { label: '设备数', prop: 'deviceCount',minWidth: '80' },
  { label: '健康顾问数', prop: 'healthDoctorCount',minWidth: '100' }
]);
let tableButtons = reactive([
  //来源于数据
  {
    id: 3,
    type: 'primary',
    label: '添加',
    perms: 'org:btn:create',
    onClick: async () => {
      showDialog.value = true
      dialogDatas = {
        title: '新增',
        type: 'add',
        // datas: dialogForConfigDatas
        institutionStatusEnumDatas: institutionStatusEnumDatas, //状态下拉数据
        cutomerLevelEnumDatas: cutomerLevelEnumDatas,//客户级别下拉数据
        institutionSourceEnumDatas: institutionSourceEnumDatas,//客户级别下拉数据
        institutionTypeEnumDatas: institutionTypeEnumDatas,//客户类型下拉数据
        industryTyeEnumDatas: industryTyeEnumDatas,//行业类型下拉数据
        salesOptionsDatas: salesOptionsDatas,//我方销售人员下拉数据
      };
    }
  },
  {
    id: 10,
    type: '',
    label: '导出',
    perms: 'org:btn:export',
    onClick: async(row:{}) => {
      const params=Object.assign({},searchFormParams,{pageNum: page.page, pageSize: page.pageSize })
      const data: any =  await exportRequest(params)
      if (data.code === 2000) {
        ElMessage.success('导出成功');
      }
      window.open(data.data);
    }
  },
  
  
]);
const onAddOrUpdate = (data?: Recordable) => {
  addOrUpdateRef.value.handleDialog(true);
  addOrUpdateRef.value.init(data);
};
const onRechargeable = (data?: Recordable) => {
  rechargeableRef.value.init(data);
};
const onPackage = (data?: Recordable) => {
  packageRef.value.init(data);
};
const onRechargeRecord = (data?: Recordable) => {
  rechargeRecordRef.value.init(data);
};

const rechargeDatas = reactive({
  rechargePoints: '', //充值检测点数		true
  amount: '', //金额		true
  paymentVoucherUrl: '' //付款凭证
});

const packageDatas = reactive([
  {
    id: 1,
    mealName: 'A1',
    points: '1222',
    isSelect: true,
    isDefault: false
  },
  {
    id: 2,
    mealName: 'A2',
    points: '1444',
    isSelect: false,
    isDefault: false
  },
  {
    id: 3,
    mealName: 'A3',
    points: '',
    isSelect: false,
    isDefault: false
  }
]);
let itemsButtons = reactive([

  {
    id: 2,
    type: 'success',
    label: '查看',
    perms: 'org:btn:view',
    onClick: (row: Row) => {
      // router.push('/myTest');
      showDialog.value = true
      dialogDatas = {
        title: '查看',
        type: 'check',
        datas: row,
        institutionStatusEnumDatas: institutionStatusEnumDatas, //状态下拉数据
        cutomerLevelEnumDatas: cutomerLevelEnumDatas,//客户级别下拉数据
        institutionSourceEnumDatas: institutionSourceEnumDatas,//客户级别下拉数据
        institutionTypeEnumDatas: institutionTypeEnumDatas,//客户类型下拉数据
        industryTyeEnumDatas: industryTyeEnumDatas,//行业类型下拉数据
        salesOptionsDatas: salesOptionsDatas,//我方销售人员下拉数据
      };
    }
  },
  {
    id: 4,
    type: 'primary',
    label: '编辑',
    perms: 'org:btn:edit',
    // onClick: (row: {}) => {
    //   setDialogDefaultDatas(row);
    //   dialogDatas = {
    //     title: '编辑',
    //     type: 'edit',
    //     panelDatas: panelDatas
    //   };
    //   onAddOrUpdate(dialogDatas);
    // }
    onClick: (row: Row) => {
      showDialog.value = true
      dialogDatas = {
        title: '编辑',
        type: 'edit',
        datas: row,
        institutionStatusEnumDatas: institutionStatusEnumDatas, //状态下拉数据
        cutomerLevelEnumDatas: cutomerLevelEnumDatas,//客户级别下拉数据
        institutionSourceEnumDatas: institutionSourceEnumDatas,//客户级别下拉数据
        institutionTypeEnumDatas: institutionTypeEnumDatas,//客户类型下拉数据
        industryTyeEnumDatas: industryTyeEnumDatas,//行业类型下拉数据
        salesOptionsDatas: salesOptionsDatas,//我方销售人员下拉数据
      };
    }
  },
  {
    id: 5,
    type: 'primary',
    label: '充值',
    perms: 'org:btn:charge',
    onClick: (row: []) => {
      // console.log('row', row);
      // onAddOrUpdate(row);
      dialogDatas = {
        title: '充值',
        type: 'edit',
        datas: rechargeDatas,
        row: row
      };
      onRechargeable(dialogDatas);
    }
  },

  {
    id: 6,
    eName: 'pause',
    perms: 'org:btn:cooperate',
    statusConfig:{
        1:'合作',
        2:'暂停合作',
        // 3:'待激活',
        // 4:'欠费暂停'
      },
      hideConfig:[3,4],
    onClick: async (row: Row) => {
      await pauseOrgRequest({ orgId: row.id, status: row.status===1?2:1 });
      getorgStatisticsFun()
      getList();
    }
  },
  {
    id: 7,
    type: 'success',
    perms: 'org:btn:chargelist',
    label: '充值记录',
    onClick: async (row: []) => {
      dialogDatas = {
        title: '充值记录',
        row: row
      };
      onRechargeRecord(dialogDatas);
    }
  },
  {
    id: 8,
    type: 'primary',
    perms: 'org:btn:package',
    label: '合作套餐',
    onClick: (row: []) => {
      dialogDatas = {
        title: '设置合作套餐',
        datas: packageDatas,
        row: row
      };

      onPackage(dialogDatas);
    }
  }
]);
const contentList = reactive([
  {
    title: '本月新增机构',
    number: '',
    bgUrl: 'Bg.png',
    iconUrl: 'Icon.png'
  },
  {
    title: '机构总数',
    number: '',
    bgUrl: 'Bg2.png',
    iconUrl: 'Icon2.png'
  },
  {
    title: '合作中机构',
    number: '',
    bgUrl: 'Bg3.png',
    iconUrl: 'Icon3.png'
  },
  {
    title: '暂停合作机构',
    number: '',
    bgUrl: 'Bg4.png',
    iconUrl: 'Icon4.png'
  },
  {
    title: '待激活机构',
    number: '',
    bgUrl: 'Bg5.png',
    iconUrl: 'Icon5.png'
  }
]);

/* 高级搜索重置 */
const handleResetFormDatas = () => {
  searchFormParams={}
  searchForm.forEach((item) => {
    if (item.value) {
      if (item.type === 'cascader') {
        item.value = [];
      } else {
        item.value = '';
      }
    }
  });
 getList();

};

const chanFormValue=(formParamsDatats:{})=>{
  searchFormParams=formParamsDatats
  // Object.assign(searchFormParams, formParamsDatats);
}
let searchFormParams = reactive({
}); //查询参数
  const { tableData, page, loading, getList, resetParams, handleCurrentChange, handleSizeChange } =
  useTable({
    apiFn: orgGetOrgListRequest,
    params: ()=>searchFormParams
  });
const panelDatas = reactive([
  {
    title: '基础信息',
    datas: [
      {
        type: 'input',
        value: '',
        label: '公司名称/组织机构名称',
        eName: 'orgName',
        placeholder: '公司名称/组织机构名称'
      },
      {
        type: 'select',
        value: '',
        label: '行业类型',
        placeholder: '行业类型',
        options: () => industryTyeEnumDatas,
        eName: 'industryType'
      },

      {
        type: 'cascader',
        value: [],
        label: '所在地区',
        placeholder: '请输入所在地区',
        eName: 'area',
        keys: ['provinceId', 'cityId', 'districtId']
      },
      {
        value: '',
        label: '邮编',
        placeholder: '请输入邮编',
        type: 'input',
        eName: 'postalCode'
      },

      {
        type: 'input',
        value: '',
        label: '联系人',
        placeholder: '请输入联系人',
        eName: 'contactPerson'
      },
      {
        type: 'input',
        value: '',
        label: '职位',
        placeholder: '请输入职位',
        eName: 'position'
      },
      {
        type: 'input',
        value: '',
        label: '手机号码',
        placeholder: '请输入手机号码',
        eName: 'phoneNumber'
      },
      {
        type: 'input',
        value: '',
        label: '微信',
        placeholder: '请输入微信',
        eName: 'wechat'
      },
      {
        type: 'input',
        value: '',
        label: '邮箱',
        placeholder: '请输入邮箱',
        eName: 'email'
      }
    ]
  },
  {
    title: '公司详情',
    datas: [
      {
        type: 'upload',
        value: '',
        label: '公司营业执照',
        eName: 'businessLicense'
      },
      {
        type: 'input',
        value: '',
        label: '详细地址',
        placeholder: '请输入详细地址',
        eName: 'addressDetails'
      },

      {
        type: 'input',
        value: '',
        label: '电话',
        placeholder: '请输入电话',
        eName: 'companyPhone'
      },
      {
        type: 'input',
        value: '',
        label: '网址',
        placeholder: '请输入网址',
        eName: 'website'
      },

      {
        type: 'textarea',
        value: '',
        label: '公司介绍/备注',
        placeholder: '请输入公司介绍/备注',
        eName: 'companyDescription'
      }
    ]
  },
  {
    title: '财务信息',
    datas: [
      {
        type: 'input',
        value: '',
        label: '税号/组织机构代码证号码',
        placeholder: '请输入税号/组织机构代码证号码',
        eName: 'taxIdOrOrgCode'
      },
      {
        type: 'input',
        value: '',
        label: '发票抬头',
        placeholder: '请输入发票抬头',
        eName: 'invoiceTitle'
      },
      {
        type: 'input',
        value: '',
        label: '开户银行',
        placeholder: '请输入开户银行',
        eName: 'bankName'
      },
      {
        type: 'input',
        value: '',
        label: '银行账号',
        placeholder: '请输入银行账号',
        eName: 'bankAccount'
      },
      {
        type: 'input',
        value: '',
        label: '电话号码',
        placeholder: '请输入电话号码',
        eName: 'telephone'
      },
      {
        type: 'input',
        value: '',
        label: '单位地址',
        placeholder: '请输入单位地址',
        eName: 'companyAddress'
      }
    ]
  },
  {
    title: '组织信息',
    datas: [
      {
        type: 'input',
        value: '',
        label: '组织ID',
        placeholder: '请输入组织ID',
        eName: 'id',
        isDisabled:true
      },
      {
    type: 'select',
    value: '',
    label: '我方销售人员',
    options: () => {
      return salesOptionsDatas;
    },
    eName: 'salesPersonId'
  },

      {
        type: 'select',
        value: '',
        label: '客户级别',
        placeholder: '客户级别',
        options: () => cutomerLevelEnumDatas,
        eName: 'customerLevel'
      },
      {
        type: 'date',
        value: '',
        label: '合作开始时间',
        placeholder: '请输入合作开始时间',
        eName: 'cooperationStartDate'
      },
      {
        type: 'select',
        value: '',
        label: '账期类型',
        options: () => orgTypeEnumDatas,
        eName: 'institutionType'
      },

      {
        type: 'input',
        value: '',
        label: '账期额度',
        placeholder: '请输入账期额度',
        eName: 'creditLimitPoints'
      },
      {
        type: 'input',
        value: '',
        label: '组织管理员手机号',
        placeholder: '请输入组织管理员手机号',
        eName: 'adminPhone'
      },
      {
    type: 'select',
    value: '',
    label: '来源',
    options: () => {
      return institutionSourceEnumDatas;
    },
    eName: 'source'
  },
    ]
  }
]);
const onCancel = () => {
  //新增，查看，编辑弹出框按钮取消事件
  addOrUpdateRef.value.handleDialog(false);

  clearFormDatas();
};

const onConfirm =async (datas: {}, type: any) => {
  //新增，查看，编辑弹出框按钮确定事件
  // multipleSelection = val;
  let data=null

  if (type === 'edit') {
    //编辑

    data= await editOrgRequest(datas);
  } else {
    //新增
    data= await addOrgRequest(datas);
  }
  if (data.code === 2000) {
    const text=type === 'edit'?'编辑成功':'新增成功'
        ElMessage.success(text);
      }
  clearFormDatas();
  addOrUpdateRef.value.handleDialog(false);
  getList();
};

/*清除表单值 */
const clearFormDatas = () => {
  panelDatas.forEach((panel) => {
    panel.datas.forEach((p) => {
      p.value = null;
    });
  });
};
const tableButtonsPermission = (datas: any[], datas1: any[]) => {
  return datas.filter(function (item1: { perms: string }) {
    return datas1.find(function (item2: { perms: string }) {
      return item1.perms === item2.perms;
    });
  });
};
// banner 数量统计
const getorgStatisticsFun = async () => {
  const data: any = await orgStatisticsRequest({});
  let currentData = data.data;
  contentList[0].number = currentData.newInstitutions;
  contentList[1].number = currentData.totalInstitutions;
  contentList[2].number = currentData.collaboratingInstitutions;
  contentList[3].number = currentData.pausedInstitutions;
  contentList[4].number = currentData.pendingActivations;
};
getorgStatisticsFun();
//设置弹出框内表单回显数据
const setDialogDefaultDatas = async (row: { id: number }) => {
  currentClickRowDatas.value = row;
  const data: any = await getOrgDetailRequest({ orgId: row.id });
  panelDatas.forEach((panel) => {
    panel.datas.forEach((p) => {
      if (p.type === 'cascader') {
        p.value=[]
      p.keys.forEach((key, i) => {
        p.value.push(data.data[key]?.toString());
      });
      // p.value=["5","164","10579"]
      return;
    }
    // if(p.type === 'upload'){
    //   p.value='http://fwjiqi.oss-cn-hangzhou.aliyuncs.com/file/e8bcfcd6-a4b5-4fa3-9dcb-4fafdf49f98f.png'
    //   return
    // }
      p.value = data.data[p.eName];
    });
  });
};
const updateList = () => {
  getList();
  getorgStatisticsFun();
  showDialog.value = false
}
/* 获取设备状态数据 */
const getInstitutionStatusEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionStatusEnum' });
  institutionStatusEnumDatas = data.data;
};
/* 获取客户级别下拉数据 */
const getCutomerLevelEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'CutomerLevelEnum' });
  cutomerLevelEnumDatas = data.data;
};
/* 获取来源下拉数据 */
const getInstitutionSourceEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionSourceEnum' });
  institutionSourceEnumDatas = data.data;
};

/* 获取客户类型下拉数据 */
const getInstitutionTypeEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionTypeEnum' });
  institutionTypeEnumDatas = data.data;
};

/* 获取行业类型下拉数据 */
const getIndustryTyeEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'IndustryTyeEnum' });
  industryTyeEnumDatas = data.data;
};
/* 获取组织类型下拉数据 */
const getOrgTypeEnumDatas = async () => {
  const data: any = await getEnumListRequest({ enumName: 'InstitutionTypeEnum' });
  orgTypeEnumDatas = data.data;
};

/* 获取组织类型下拉数据 */
const getSalesOptionsDatas = async (datas:{name:''}) => {
  const data: any = await salesOptionsRequest(datas);
  salesOptionsDatas = data.data;
};



onMounted(() => {
  getInstitutionStatusEnumDatas(); //状态下拉数据
  getCutomerLevelEnumDatas(); //客户级别下拉数据
  getInstitutionSourceEnumDatas(); //获取来源下拉数据
  getInstitutionTypeEnumDatas(); //获取客户类型下拉数据
  getIndustryTyeEnumDatas(); //获取行业类型下拉数据
  getOrgTypeEnumDatas(); //获取组织类型下拉数据
  getSalesOptionsDatas({name:''}); //获取我方销售人员下拉数据
  if(!currentMenudatas.value) {
    return
  }
  tableButtons = tableButtonsPermission(tableButtons, currentMenudatas.value.tableButtons); //tableButtons根据数据返回按钮信息控制权限
  itemsButtons = tableButtonsPermission(itemsButtons, currentMenudatas.value.itemsButtons); //itemButtons根据数据返回按钮信息控制权限
});

</script>
<style scoped>
.packageCardcontainer {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
  > .card {
    flex: 0 0 18%;
    min-width: 18%;
    margin-right: calc(9.99% / 4);
    /* // 每行最后一个卡片 */
    &:nth-child(5n) {
      margin-right: 0;
    }

    /* // 最后一个卡片 */
    &:last-child {
      margin-right: auto;
    }
  }
}
</style>
